<template>
  <Page v-slot:default="{contentClass}" :style="{backgroundColor: item?.coupon_tpl?.color}">
    <div :class="contentClass" v-if="item">
      <div class="ml-4 mr-4 bg-white shadow flex flex-col justify-center items-center p-2 rounded-sm pb-8 qrcode_box">
        <div class=" text-gray-500 text-sm mt-4">植得口腔</div>
        <div class=" font-bold text-xl mt-2 text-gray-700">{{item.coupon_tpl?.name}}</div>
        <canvas class="qrcode" ref="qrcode"></canvas>
        <canvas class="qroffwrite mt-8" ref="offwrite" :width="offwriteWidth" :height="offwriteHeight"></canvas>
        <div class="tracking-widest font-bold" :style="{color: item.coupon_tpl.color}">{{item.no.replaceAll(/(\w{4})/g, '$1 ')}}</div>
      </div>
    </div>
  </Page>
</template>

<script setup>
import {nextTick, ref} from 'vue';
import {useStore} from "vuex";
import {useRoute, useRouter} from "vue-router";
import Page from "../../components/Page.vue"
import QRCode from "qrcode";
import {computed, onMounted, watch} from "vue";

import {getPx} from "../../utils/rem"
import apis from '../../apis'

const store = useStore()
const router = useRouter()
const route = useRoute()

const item = ref(null)

const offwriteWidth = 10 * parseFloat(getPx()) // 20rem
const offwriteHeight = 10 * parseFloat(getPx()) // 20rem

const code = ''
const qrcode = ref(null)
const offwrite = ref(null)

const showQrcode = (code) => {
  return new Promise((resolve, reject) => {
    QRCode.toCanvas(qrcode.value, code, {
      scale: 6, // default: 4
      width: parseFloat(getPx()),
    }, (error) => {
      if (error) {
        reject(error)
      } else {
        resolve()
      }
    })
  }).then(() => {
    const canvasCode = qrcode.value
    const contextCode = canvasCode.getContext("2d")
    const contextOffwrite = offwrite.value.getContext("2d")
    contextOffwrite.width = offwriteWidth
    contextOffwrite.height = offwriteHeight
    const codeImg = contextCode.getImageData(0, 0, canvasCode.width, canvasCode.height)
    contextOffwrite.putImageData(codeImg, (offwriteWidth - canvasCode.width) / 2, (offwriteHeight - canvasCode.height) / 2, 0, 0, canvasCode.width, canvasCode.height)
  })
}

apis.coupon.show_coupon(route.query.id, {}).then(({data: result}) => {
  item.value = result.data
  console.log(item.value.no)
  nextTick(() => {
    showQrcode(item.value.no)
  })
})
</script>

<style scoped>
.qrcode_box .qrcode{
  width: 0rem!important;
  height: 0rem!important;
}
</style>